﻿using MD5Hash;
using MediatR;
using MS.Data.API.Write.Applicant.Command.User;
using MS.Data.API.Write.DTO.User;
using MS.Data.Domain;
using MS.Data.ErrorCode;
using MS.Data.Infratructrue.Istanbul;

namespace MS.Data.API.Write.Applicant.CommandHandel.User
{
    public class UpdateUserCommandHandel : IRequestHandler<UpdateUserCommand, APIResult<int>>
    {
        IBaseRepository<Domain. User> userRep;

        IBaseRepository<Role> roleRep;
        public UpdateUserCommandHandel(IBaseRepository<Domain.User> userRep, IBaseRepository<Role> roleRep)
        {
            this.userRep = userRep;

            this.roleRep = roleRep;
        }

        public async Task<APIResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.code = APIEnum.更新成功;
            result.mes = APIEnum.更新成功.ToString();

            var mi = request.UserPwd.GetMD5();
            var res = userRep.GetAll().FirstOrDefault(s => s.UserId == request.UserId);

            res.UserName= request.UserName;
            res.UserPwd = mi;
            res.NickName= request.NickName;
            res.CreaTime = DateTime.Now;

            var list=roleRep.GetAll().FirstOrDefault(s=>s.RoleId == request.RoleId);

            list.RoleName= request.RoleName;

            await userRep.Update(res);
            await roleRep.Update(list);

            return await Task.FromResult(result);
        }
    }
}
